<?php

namespace addons\booking\controller;

use addons\booking\model\Order as OrderModel;
use addons\third\model\Third;
use addons\booking\model\Cart;
use fast\Date;
use think\Config;
use think\Db;

class Order extends Base
{
    protected $noNeedLogin = ['epay'];

    /**
     * 创建订单
     */
    public function add()
    {
        $source_id = $this->request->post('id');
        $type = $this->request->post('type/d');
        $platform = $this->request->post('platform'); //百度小程序到店付
        if (empty($source_id)) {
            $this->error('参数缺失');
        }
        //组合参数
        $param = [];
        $param['user_coupon_id'] = $this->request->post('user_coupon_id/d'); //用户优惠券的id
        $param['memo'] = $this->request->post('memo');
        $param['platform'] = $platform;
        $param['user_id'] = $this->auth->id;
        $config = get_addon_config('booking');

        switch ($type) {
            case 0: //房间
                $start_time = $this->request->post('start_time');
                $end_time = $this->request->post('end_time');
                $lodger_ids = $this->request->post('lodger_ids/a'); //住客资料

                if (empty($start_time) || empty($end_time)) {
                    $this->error('请选择入住和离店日期');
                }
                //判断数据格式是否正确
                if (!checkDateFormat($start_time) || !checkDateFormat($end_time)) {
                    $this->error('日期格式不正确');
                }
                if (empty($lodger_ids)) {
                    $this->error('请选择住客信息');
                }
                $maxDays = intval(isset($config['max_order_days']) ? $config['max_order_days'] : 90);
                $maxDate = Date::unixtime('day', $maxDays);
                if (strtotime($end_time) > $maxDate) {
                    $this->error('最长可预订不超过' . date("Y-m-d", $maxDate) . '的房间');
                }
                $param['source_id'] = $source_id; //房间id
                $param['start_time'] = strtotime($start_time);
                $param['end_time'] = strtotime($end_time);
                $param['lodger_ids'] = $lodger_ids;
                $param['nums'] = count($lodger_ids);
                break;
            case 1: //商品
                $param['house_number'] = $this->request->post('house_number');
                if (!$param['house_number'] && !$param['memo']) {
                    $this->error('请输入房间号或备注');
                }
                //为购物车id
                //校验购物车id 合法
                // $row = (new Cart)->where('id', 'IN', $source_id)->where('user_id', '<>', $this->auth->id)->find();
                $cw["id"]=["in",$source_id];
                $cw["user_id"]= $this->auth->id;
                $row = \think\Db::table("rzjd_booking_goods_cart")->where($cw)->find();
                if (!$row) {
                    $this->error('存在不合法购物车数据');
                }
                $goodsdata=\think\Db::table("rzjd_booking_goods")->where(["id"=>$row["goods_id"]])->find();
                if($goodsdata){
                    $goodscategory=\think\Db::table("rzjd_booking_goods_category")->where("id","in",$goodsdata["category_ids"])->find();
                    $param['type'] = $goodscategory["types"]; //购物车id
                }
                $param['cart_ids'] = $source_id; //购物车id
                break;
            default:
                $this->error('不存在的订单类型');
        }
        $order = null;
        
            $parent_id=$this->request->post('parentid');
        try {
            if($parent_id && $parent_id>0){
                binding($this->auth->id,$parent_id);
            }
            $order = OrderModel::add($type, $param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('下单成功！', $order);
    }


    /**
     * 订单列表
     */
    public function orderList()
    {
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $this->success('', OrderModel::tableList($param));
    }

    /**
     * 订单详情
     */
    public function detail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $order = OrderModel::getDetail($id, $this->auth->id);
        $this->success('', $order);
    }


    /**
     * 订单支付
     */
    public function pay()
    {
        $id = $this->request->post('id');
        $paytype = $this->request->post('paytype');
        $method = $this->request->post('method');
        $appid = $this->request->post('appid'); //为APP的应用id
        $returnurl = $this->request->post('returnurl', '', 'trim');
        $openid = '';

        //非H5 支付,非余额
        if (in_array($method, ['miniapp', 'mp'])) {
            $info = get_addon_info('third');
            if (!$info || !$info['state']) {
                $this->error("请在后台安装第三方登录插件");
            }
            $third = Third::where('platform', 'wechat')
                ->where('apptype', $method)
                ->where('user_id', $this->auth->id)
                ->find();

            if (!$third) {
                $this->error("未找到微信授权的用户信息", 'bind');
            }
            $openid = $third['openid'];
        }
        $response = null;
        try {
            $response = OrderModel::pay($id, $this->auth->id, $paytype, $method, $openid, '', $returnurl);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success("请求成功", $response);
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }
        $order = OrderModel::get($id);
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->user_id != $this->auth->id) {
            $this->error('不能越权操作');
        }
        if ($order->status == 'expired') {
            $this->error('订单已失效！');
        }
        if ($order->status == 'canceled') {
            $this->error('订单已取消！');
        }
        if ($order->status == 'refunding') {
            $this->error('订单退款中！');
        }
        if (in_array($order->status, ['evaluate', 'finished'])) {
            $this->error('订单不能再取消！');
        }
        // 启动事务
        Db::startTrans();
        try {

            if ($order['type'] == 0) {
                //在规定时间内取消可以退款
                if ($order->status == 'paid' && ($order['checkin_time'] - time()) > Config::get('booking.distance_checkin_time')) {
                    $order->status = 'refunding';
                } else {
                    $order->status = 'canceled';
                }
            } else {
                if ($order->status == 'paid') {
                    $order->status = 'refunding';
                } else {
                    $order->status = 'canceled';
                }
            }
            $order->save();
            //商品库存恢复
            if ($order['type'] == 1) {
                $goods = $order->source()->with('Goods')->select();
                foreach ($goods as $item) {
                    if ($item->goods) {
                        $item->goods->setInc('stocks', $item->nums);
                    }
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('订单取消失败');
        }
        $this->success('订单取消成功！', $order['status']);
    }

    /**
     * 确认收到
     */
    public function receiving()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }
        $order = OrderModel::get($id);
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->user_id != $this->auth->id) {
            $this->error('不能越权操作');
        }
        if ($order->status != 'shipped') {
            $this->error('订单不是配送中');
        }
        $order->status = 'evaluate';
        $order->save();
        $this->success('确认收货成功');
    }

    /**
     * 退房
     */
    public function orderCheckout()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }
        $order = OrderModel::get($id);
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->user_id != $this->auth->id) {
            $this->error('不能越权操作');
        }
        if ($order->status == 'checkouting') {
            $this->error('正在退房中，请稍后！');
        }
        if ($order->status != 'checkined') {
            $this->error('不能越权操作');
        }
        $order->status = 'checkouting';
        $order->save();
        $this->success('退房申请成功！');
    }

    /**
     * 支付回调
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                \addons\booking\model\Order::settle($data['out_trade_no'], $payamount);
            } catch (\Exception $e) {
                \think\Log::write($e->getMessage(), 'epay');
            }
            echo $pay->success();
        }
        return;
    }
}
